import Request from 'luch-request'
import getSign from "./sign"
import store from '../store/index'

const serve = new Request();

let isRefreshToken = false
let requests = []

serve.setConfig((config) => { /* config 为默认全局配置*/
	config.baseURL = 'http://api.sanye666.top'; /* 根域名 */
	config.header = {
		'content-type': 'application/x-www-form-urlencoded'
	};
	timeout: 10000
	return config
})

serve.interceptors.request.use((config) => {
	let timeStramp = Math.round(new Date().getTime() / 1000).toString();
	let sign = getSign(timeStramp);
	config.data = { ...config.data,
		timeStramp,
		sign
	};
	if(store.state.global.token){
		config.header['Authorization'] = 'Bearer ' + store.state.global.token
	}
	return config
}, config => {
	return Promise.reject(config)
})

serve.interceptors.response.use((response) => {
	const res = response;
	if (!res.data || res.data.code !== 200) {
		if (res.data.code == 4011) {
			return handleRefreshToken(response)
		}
		uni.showToast({
			title: res.data.message || '服务器开小差了~',
			duration: 2000,
			icon: 'none'
		});
		return Promise.reject(res);
	} else {
		return res.data;
	}
}, (response) => {
	const pages = getCurrentPages()
	if (pages[pages.length - 1].route !== 'pages/error/index') {
		uni.navigateTo({
			url: '/pages/error/index'
		})
	}
	return Promise.reject(response);
})

async function handleRefreshToken(response) {
	try {
		if (isRefreshToken) {
			return new Promise((resolve) => {
				requests.push((token) => {
					response.config.header['Authorization'] = 'Bearer ' + token
					resolve(serve.request(response.config))
				})
			})
		} else {
			isRefreshToken = true
			const token = await store.dispatch('refreshToken')
			response.config.header['Authorization'] = 'Bearer ' + token
			requests.forEach((cb) => cb(token))
			requests = []
			const result = await serve.request(response.config)
			isRefreshToken = false
			return result
		}
	} catch (e) {
		console.log(e)
		isRefreshToken = false
	}
}

export default serve
